package com.goodrain.oauth2demo.controller;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

@RestController
@RequestMapping("/")
public class Oauth2Controller {
    public String state = "xyz";

    public String authServerURL = System.getenv("SERVER_URL");

    public Config config = new Config(System.getenv("CLIENT_ID"), System.getenv("CLIENT_SECRET"), new String[]{"all"}, System.getenv("REDIRECT_URL"),
            authServerURL, authServerURL + "/authorize", authServerURL + "/token");


    @GetMapping("/")
    public RedirectView index(RedirectAttributes attributes) {
        return new RedirectView(config.AuthCodeURL(this.state));
    }

    @GetMapping("/oauth2")
    @ResponseBody
    public String oauth2(@RequestParam(name = "state") String state,
                       @RequestParam(name = "code") String code) throws Exception {
        if (!state.equals(this.state)) {
            throw new Exception("State invalid");
        }
        if (code.equals("")) {
            throw new Exception("Code not found");
        }

        // retrieve token
        return config.retrieveToken(code);
    }

    @GetMapping("/userinfo")
    @ResponseBody
    public String userInfo(@RequestParam(name = "token") String token) throws Exception {
        String url = authServerURL + "/oauth/userinfo";

        Request request = new Request.Builder()
                .addHeader("Authorization", token)
                .get()
                .url(url)
                .build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        if (response.code() != 200) {
            throw new Exception(response.message());
        }
        return response.body().string();
    }
}
